问题描述(难度中等-347)
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
1 | Input: nums = [1,1,1,2,2,3], k = 2 |
Example 2:
1 | Input: nums = [1], k = 1 |
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.
方法一:HashMap+PriorityQueue
复杂度分析摘录
Complexity Analysis
- Time complexity : O(Nlog(k). The complexity of
Counter
method is O(N). To build a heap and output list takes O(Nlog(k)). Hence the overall complexity of the algorithm is O(N + Nlog(k)) =O(Nlog(k)). - Space complexity : O(N) to store the hash map.
实现代码
通过HashMap进行计算,再通过优先级队列最小堆找出前k个出现最多的。时间复杂度O(N*log(k)),空间复杂度O(N)。
1 |
|
这里主要需要定义一个比较器,传送给PriorityQueue。
方法二:Map+TreeMap
这个方法相当于对搜集的结果进行全排序,时间复杂度O(N*log(N)),空间复杂度O(N)。
1 | package P347; |